<template>
  <div class="content-wrap">
    <adv-button type="primary" @click="handkeAdd">新增</adv-button>
    <!-- <adv-button type="primary" @click="handkeDetail(0)">查找</adv-button> -->
    <adv-table :tableConfig="tableConfig"> </adv-table>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import {
  getTeacherList,
  updateTeacherOne,
  addTeacherOne,
  deleteTeacherOne,
} from "@/api";
import { Modal } from "@leisure-lib/ui";
import Add from "./add.vue";
import { ElMessage } from "element-plus";

const tableConfig = ref({
  columns: [
    {
      label: "ID.",
      prop: "id",
      width: 100,
    },
    {
      label: "姓名",
      prop: "name",
      width: 200,
    },
    {
      label: "电话",
      prop: "phone",
    },
    {
      label: "操作",
      type: "options",
      btns: [
        { text: "编辑", func: (item) => handkeDetail(item) },
        { text: "删除", func: (item) => handleDelete(item) },
      ],
    },
  ],
  pagination: {
    total: 0,
    currentPage: 1,
    pageSize: 10,
  },
  listData: [],
  initData: (params) => initTableData(params),
});

const initTableData = (arg = {}) => {
  const params = {
    ...arg,
    id: 111,
  };
  return getTeacherList(params).then((res) => {
    tableConfig.value.listData = res;
    tableConfig.value.pagination.total = res.length;
  });
};

const handkeAdd = () => {
  Modal.open(Add, {
    width: 500,
    title: "新增",
    onOk: (comp, modal) => {
      comp.formRef.validate().then((res) => {
        if (res) {
          const params = { ...comp.form };
          addTeacherOne(params).then((res) => {
            ElMessage.success("操作成功");
            initTableData();
            modal.close();
          });
        }
      });
    },
  });
};

const handkeDetail = (row) => {
  Modal.open(Add, {
    width: 500,
    title: "编辑",
    id: row.id,
    onOk: (comp, modal) => {
      comp.formRef.validate().then((res) => {
        if (res) {
          const params = { ...comp.form, id: row.id };
          updateTeacherOne(params).then((res) => {
            ElMessage.success("操作成功");
            initTableData();
            modal.close();
          });
        }
      });
    },
  });
};

const handleDelete = (row) => {
  Modal.open("是否确认删除该数据？", {
    width: 350,
    title: "删除",
    onOk: (comp, modal) => {
      deleteTeacherOne(row.id).then((res) => {
        ElMessage.success("操作成功");
        initTableData();
        modal.close();
      });
    },
  });
};
</script>

<style lang="less" scoped></style>
